import _ from 'lodash';
import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';

export default defineStore('LoginInfo', () => {
  // 状态
  const loginInfo = ref<Partial<LoginInfo>>({});

  const loginHistory = ref<LoginInfo[]>([]);

  // 计算属性
  async function isLoggedIn() {
    // return !!(loginInfo.value?.token && loginInfo.value?.username)
    let ret = false;
    ret = !!(loginInfo.value?.token);
    // if (ret) {....}
    return ret;
  }

  const hasLoginHistory = computed(() => {
    return loginHistory.value.length > 0;
  });

  // 方法
  const setLoginInfo = (info: LoginInfo) => {
    _.merge(loginInfo.value, info);
    localStorage.setItem('LCC_INFO', JSON.stringify(loginInfo.value));
  };

  const clearLoginState = async () => {
    localStorage.removeItem('LCC_INFO');
    sessionStorage.clear();
    loginInfo.value = { username: '', token: '' };
  };

  const getLoginHistory = async (): Promise<LoginInfo[]> => {
    const history = localStorage.getItem('LCC_LOGIN_HISTORY');
    const parsedHistory = history ? JSON.parse(history) : [];
    loginHistory.value = parsedHistory;
    return parsedHistory;
  };

  const saveLoginHistory = async (info: LoginInfo): Promise<void> => {
    if (!info.username || !info.token) {
      return;
    }

    const history = localStorage.getItem('LCC_LOGIN_HISTORY');
    const parsedHistory = history ? JSON.parse(history) : [];

    // 移除已存在的相同用户名记录
    const existingIndex = parsedHistory.findIndex((h: LoginInfo) => h.username === info.username);
    if (existingIndex !== -1) {
      parsedHistory.splice(existingIndex, 1);
    }

    // 添加新记录
    parsedHistory.push(info);

    // 保存到 localStorage
    localStorage.setItem('LCC_LOGIN_HISTORY', JSON.stringify(parsedHistory));
    loginHistory.value = parsedHistory;
  };

  const deleteLoginHistory = async (index: number): Promise<void> => {
    loginHistory.value.splice(index, 1);
    localStorage.setItem('LCC_LOGIN_HISTORY', JSON.stringify(loginHistory.value));
  };

  const clearLoginHistory = async (): Promise<void> => {
    loginHistory.value = [];
    localStorage.removeItem('LCC_LOGIN_HISTORY');
  };

  // 初始化：从 localStorage 恢复登录信息
  const initialize = () => {
    try {
      const savedInfo = localStorage.getItem('LCC_INFO');
      if (savedInfo) {
        loginInfo.value = JSON.parse(savedInfo);
      }
    } catch (error) {
      console.error('恢复登录信息失败:', error);
      loginInfo.value = { username: '', token: '' };
    }
  };

  // 监听登录信息变化，自动保存到 localStorage
  watch(loginInfo, (newInfo) => {
    if (newInfo.username || newInfo.token) {
      localStorage.setItem('LCC_INFO', JSON.stringify(newInfo));
    }
  }, { deep: true });

  // 初始化
  initialize();

  return {
    // 状态
    loginInfo,
    loginHistory,

    // 计算属性
    isLoggedIn,
    hasLoginHistory,

    // 方法
    setLoginInfo,
    clearLoginState,
    getLoginHistory,
    saveLoginHistory,
    deleteLoginHistory,
    clearLoginHistory,
    initialize
  };
});
